package com.java.cg.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.java.cg.goods.entity.Sku;
import com.java.cg.goods.entity.Spu;
import com.java.cg.goods.feign.GoodsApi;
import com.java.cg.order.constants.CartConstant;
import com.java.cg.order.entity.OrderItem;
import com.java.cg.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jiangli
 * @since 2020/2/17 19:35
 */
@Service
public class CartServiceImpl implements CartService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private GoodsApi goodsApi;

	@Override
	public void addCart(Integer count, Long skuId, String username) {
		if (count <= 0) {
			redisTemplate.boundHashOps(CartConstant.CG_CART + username).delete(skuId.toString());
			// 如果购物车没有数据则清除购物车
			Long size = redisTemplate.boundHashOps(CartConstant.CG_CART + username).size();
			if (size == null || size == 0) {
				redisTemplate.delete(CartConstant.CG_CART + username);
			}
			return;
		}

		// 查询商品信息
		Sku sku = goodsApi.getSkuInfoBySkuId(skuId);
		Spu spu = goodsApi.findSpuById(sku.getSpuId());
		// 构建OrderItem对象
		OrderItem orderItem = fetchOrderItem(sku, spu, count);
		// 将商品添加到购物车保存到redis中
		redisTemplate.boundHashOps(CartConstant.CG_CART + username).put(skuId.toString(), JSON.toJSONString(orderItem));

	}

	@Override
	public List<OrderItem> list(String username) {
		List<Object> cartJsonList = redisTemplate.boundHashOps(CartConstant.CG_CART + username).values();
		List<OrderItem> orderItems = null;
		//将json字符串转换成bean
		if (!CollectionUtils.isEmpty(cartJsonList)) {
			orderItems = cartJsonList.stream().map(cartJson -> JSON.parseObject(cartJson.toString(), OrderItem.class)).collect(Collectors.toList());
		}
		return orderItems;
	}

	/**
	 * 删除购物车商品
	 * @param skuId
	 */
	@Override
	public void delete(Long skuId,String username) {
		redisTemplate.boundHashOps(CartConstant.CG_CART + username).delete(skuId);
	}

	/**
	 * 将商品信息封装OrderItem对象
	 */
	private OrderItem fetchOrderItem(Sku sku, Spu spu, Integer count) {
		OrderItem orderItem = new OrderItem();
		orderItem.setCategoryId1(spu.getCategory1Id());
		orderItem.setCategoryId2(spu.getCategory2Id());
		orderItem.setCategoryId3(spu.getCategory3Id());
		orderItem.setSkuId(sku.getId());
		orderItem.setPayMoney(count * sku.getPrice());
		orderItem.setSpuId(spu.getId());
		orderItem.setName(sku.getName());
		orderItem.setPrice(sku.getPrice());
		orderItem.setNum(count);
		orderItem.setMoney(count * sku.getPrice());
		orderItem.setImage(sku.getImage());
		orderItem.setWeight(sku.getWeight());
		orderItem.setIsReturn("0");
		return orderItem;
	}
}
